import React, { Component } from "react";
import PubSub from "pubsub-js";
import "./index.css";

export default class List extends Component {
  state = {
    userList: [],
    isFirst: true, // 第一次搜索之前展示
    isLoading: false, // 搜索的loadding
    err: "", // 错误信息
  };

  // 组件挂载完毕
  componentDidMount() {
    // 订阅消息
    this.unxie = PubSub.subscribe("updateUsers", (_, data) => {
      this.setState(data)
    });
  }
 // 组件将要卸载
  componentWillUnmount() {
    // 清除订阅
    PubSub.unsubscribe(this.unxie)
  }

  render() {
    const { userList, isFirst, isLoading, err } = this.state;
    return (
      <div>
        <ul>
          {isFirst ? (
            <h2>欢迎使用！请输入用户名搜索GitHub用户信息</h2>
          ) : isLoading ? (
            <h2>Loading...........</h2>
          ) : err ? (
            <h2 style={{ color: "red" }}>{err}</h2>
          ) : (
            userList.map((item) => {
              return (
                <li key={item.id}>
                  <a href={item.html_url} target="_blank">
                    <img src={item.avatar_url} alt="avatar" />
                  </a>
                  <p title={item.login}>{item.login}</p>
                </li>
              );
            })
          )}
        </ul>
      </div>
    );
  }
}
